using UnityEngine;
using System.Collections;

/// \class  gkAppearOnEvent
/// \brief  Make a game object appear on event
[AddComponentMenu("GK/Engine/GameCore/Animation/gkAppearOnEvent")]
public class gkAppearOnEvent : MonoBehaviour 
{
	/// The event name on which we have to appear
	public string AppearEventName;
	
	/// The appear animation clip
	public AnimationClip AppearAnimationClip;
	
	/// The disappear animation clip
	public AnimationClip DisappearAnimationClip;
	
	/// The appearence duration 
	/// < 0 = infinite
	public float AppearenceDuration = -1.0f;
	
	/// The blend time in percent of the animation duration
	public float AppearBlendTimePercent = 0.3f;
	
	/// The Hierarchy event component
	private gkEventComponent m_rEventComponent;
	
	/// Have we appeared?
	private bool m_bAppeared;
	
	/// The time since the last appearence
	private float m_fTimeSinceLastAppearence;
	
	/// Appear Event name
	private string m_strAppearEventName;
	
	/// \brief  Called before the level start to play
	void Start() 
	{	
		// Set the animation to the first frame of the appearence animation
		animation.Play(AppearAnimationClip.name);
		animation.Sample();
		animation.Stop();
	}
	
	/// \brief  Called when the component is enabled
	void OnEnable() 
	{
		// Save the appear event name
		m_strAppearEventName = AppearEventName;
		
		// Grab the event component of the hierarchy
		m_rEventComponent = transform.root.GetComponentInChildren<gkEventComponent>();
		
		// Listen the appear event of the owner
		m_rEventComponent.AddEventHandler(m_strAppearEventName, HandleAppearEvent);
	}
	
	/// \brief  Called when the component is disabled
	void OnDisable() 
	{	
		// Remove the appear event handler
		m_rEventComponent.RemoveEventHandler(m_strAppearEventName, HandleAppearEvent);
	}
	
	/// \brief  Called each frame
	void Update()
	{
		// if we have to disappear
		if(m_bAppeared && AppearenceDuration > 0)
		{
			m_fTimeSinceLastAppearence -= Time.deltaTime;
			if(m_fTimeSinceLastAppearence <= 0.0f)
			{
				// Disappear
				m_bAppeared = false;
				animation.Play(DisappearAnimationClip.name);
			}
		}
	}
	
	/// \brief  Handle the life change
	void HandleAppearEvent(Object m_rEvent)
	{
		if(m_bAppeared == false)
		{
			// Appear
			animation.CrossFade(AppearAnimationClip.name, AppearBlendTimePercent * AppearAnimationClip.length);
			m_bAppeared = true;
		}
		// Reboot appearence timer
		m_fTimeSinceLastAppearence = AppearenceDuration;
	}
}
